package cn.dsttl3.tupan.Ability.slice;

import cn.dsttl3.tupan.MyApp;
import cn.dsttl3.tupan.ResourceTable;
import cn.dsttl3.tupan.SampleItemProvider;
import cn.dsttl3.tupan.bean.baidu.BaiduBean;
import cn.dsttl3.tupan.bean.baidu.FileInfo;
import cn.dsttl3.tupan.bean.baidu.Quota;
import cn.dsttl3.tupan.utils.DataUtils;
import cn.dsttl3.tupan.utils.GlideRoundTransform;
import cn.dsttl3.tupan.utils.SizeUtil;
import cn.dsttl3.tupan.utils.baidu.BaiduFileList;
import cn.dsttl3.tupan.utils.baidu.BaiduQuota;
import cn.dsttl3.tupan.utils.baidu.BaiduUserInfo;
import cn.dsttl3.tupan.bean.baidu.UserInfo;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.dialog.PopupDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.data.preferences.Preferences;
import ohos.miscservices.timeutility.Time;
import ohos.multimodalinput.event.KeyEvent;
import java.util.List;
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;

public class IndexAbilitySlice extends AbilitySlice {
    Image imageIcon;
    Text textUserName;
    Text textUserInfo;
    String token;
    String path = "/";
    String backPath = "/";
    String rePath;


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_index);
        imageIcon = (Image) findComponentById(ResourceTable.Id_img_icon);
        textUserName = (Text) findComponentById(ResourceTable.Id_text_username);
        textUserInfo = (Text) findComponentById(ResourceTable.Id_text_userinfo);
        Preferences preferences = new DataUtils().getPreferences(getApplicationContext());
        token = preferences.getString("token",null);
        imageIcon.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                PopupDialog popupDialog = new PopupDialog(getContext(), component);
                popupDialog.setText("长按退出账号");
                popupDialog.setBackColor(Color.YELLOW);
                popupDialog.setHasArrow(true);
                popupDialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Time.sleep(1500);
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                popupDialog.destroy();
                            }
                        });
                    }
                }).start();

            }
        });

        imageIcon.setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                CommonDialog dialog = new CommonDialog(getContext());
                dialog.setTitleText("菟盘");
                dialog.setContentText("正在退出账号");
                dialog.setSize(800, MATCH_CONTENT);
                dialog.setButton(IDialog.BUTTON2, "取消", new IDialog.ClickedListener() {
                    @Override
                    public void onClick(IDialog iDialog, int i) {
                        iDialog.destroy();
                    }
                });
                dialog.setButton(IDialog.BUTTON3, "确认", new IDialog.ClickedListener() {
                    @Override
                    public void onClick(IDialog iDialog, int i) {
                        iDialog.destroy();
                        preferences.delete("token");
                        preferences.flush();
                        Intent intent1 = new Intent();
                        Operation operation = new Intent.OperationBuilder()
                                .withBundleName(MyApp.bundleName)
                                .withAbilityName("cn.dsttl3.tupan.Ability.LoginAbility")
                                .build();
                        intent1.setOperation(operation);
                        startAbility(intent1);
                        terminateAbility();
                    }
                });
                dialog.show();

            }
        });
        initView();
        initList(path);
    }

    private void initView() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String uinfoJSON = new BaiduUserInfo().get(token);
                UserInfo userInfo = new Gson().fromJson(uinfoJSON, UserInfo.class);
                String quotaJSON = new BaiduQuota().get(token);
                Quota quota = new Gson().fromJson(quotaJSON, Quota.class);
                getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        RequestOptions myOptions = new RequestOptions().transform(new GlideRoundTransform(getContext(), 48));
                        Glide.with(getContext())
                                .load(userInfo.getAvatar_url())
                                .fitCenter()
                                .apply(myOptions)
                                .into(imageIcon);
                        textUserName.setText(userInfo.getBaidu_name());
                        if (userInfo.getVip_type() == 0) {
                            textUserName.setTextColor(Color.BLACK);
                        } else {
                            textUserName.setTextColor(Color.RED);
                        }
                        textUserInfo.setText(getVIP(userInfo.getVip_type()) + "(" + new SizeUtil().getPrintSize(quota.getUsed())
                                + "/" + new SizeUtil().getPrintSize(quota.getTotal()) + ")");
                    }
                });
            }
        }).start();
    }
    private void initList(String path) {
        backPath =path;
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_file_list);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String baiduFileJSON = new BaiduFileList().getList(token + "&dir=" +path);
                List<FileInfo> fileInfoList = new Gson().fromJson(baiduFileJSON, BaiduBean.class).getList();
                getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        if (path.length() > 1){
                            FileInfo fileInfo = new FileInfo();
                            fileInfo.setServer_filename("返回上一页");
                            int index = path.lastIndexOf("/");
                            if (index == 0){
                                rePath = "/";
                            }else {
                                rePath = path.substring(0,index);
                            }
                            fileInfo.setPath(rePath);
                            fileInfo.setIsdir(1);
                            fileInfoList.add(0,fileInfo);
                        }
                        SampleItemProvider sampleItemProvider = new SampleItemProvider(fileInfoList, IndexAbilitySlice.this);
                        listContainer.setItemProvider(sampleItemProvider);
                        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
                            @Override
                            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                                if (fileInfoList.get(i).getIsdir() == 1){
                                    initList(fileInfoList.get(i).getPath());
                                }else {
                                    Intent intent = new Intent();
                                    intent.setParam("fsid",fileInfoList.get(i).getFs_id());
                                    Operation operation = new Intent.OperationBuilder()
                                            .withBundleName(MyApp.bundleName)
                                            .withAbilityName("cn.dsttl3.tupan.Ability.FileAbility")
                                            .build();
                                    intent.setOperation(operation);
                                    startAbility(intent);
                                }
                            }
                        });

                    }
                });
            }
        }).start();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    /**
     * 会员类型判断
     * @param type Vip_type
     * @return 会员类型
     */
    private String getVIP(long type){
        switch ((int) type){
            case 1:
                return "普通会员";

            case 2:
                return "超级会员";

            default:
                return "普通用户";
        }
    }

    /**
     * 防止误退出操作
     */
    boolean exit = true;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        System.out.println(backPath + backPath.length());
        // 浏览的目录不是根目录时返回上一个目录
        if (backPath.length() > 1){
            initList(rePath);
            return true;
        } else {
            if (exit){
                new ToastDialog(getContext()).setText("再次返回将退出程序").show();
                exit = false;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Time.sleep(3000);
                        exit=true;
                    }
                }).start();
                return true;
            }else {
                return false;
            }
        }
    }
}
